package com.cs.beneficios.web.action;

import com.cs.beneficios.business.entity.AreasDAO;
//import com.cs.beneficios.business.entity.AuditoriaDAO;
import com.cs.beneficios.business.entity.ProgramaDAO;
import com.cs.beneficios.business.entity.RepBeneficioOtorgadoDAO;
import com.cs.beneficios.business.entity.ReporteTotalProgramasDAO;
import com.cs.beneficios.business.entity.SubProgramaDAO;
import com.cs.beneficios.business.entity.SubprogramaSedeDAO;
import com.cs.beneficios.business.model.ProgramaVO;
import com.cs.beneficios.business.model.ReporteTotalProgramasVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.paoyer.administration.business.model.UserVO;

import java.io.IOException;

import java.sql.SQLException;

import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ReportTotalProgramasAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
    Object codePrograma =  (Object)request.getParameter("codePrograma");
    //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
	ConnectionFactory cf = new ConnectionFactory();
    HttpSession session = request.getSession();
    UserVO user = (UserVO)session.getAttribute("userInfo");
    session.removeAttribute("msg");
    session.setAttribute("msg","");
    Collection programas=null;
    Collection subprogramas=null;
    Collection areas=null;
    ProgramaDAO objProgramaDAO;
    SubProgramaDAO objSubProgramaDAO;
    
    SubprogramaSedeDAO objSubsedeDAO;
    ReporteTotalProgramasDAO  objProg;
    session.removeAttribute("Beneficios");
    String strarea = request.getParameter("codearea");
    
    try
    {
      //AuditoriaDAO objAuditoria = new AuditoriaDAO(cf);
      AreasDAO objAreaDAO = new AreasDAO(cf);
      int iCode = Integer.parseInt(String.valueOf(user.getCode()));
      //areas = objAuditoria.SelectSecretaria(iCode,user.getUserGroupName());
      areas = objAreaDAO.getAreasAuthorized(String.valueOf(user.getCode()), user.getUserGroupName());
      cf.closeConnection(objAreaDAO.getConn());
      //objProg = new ReporteTotalProgramasDAO(cf);
      //areas = objProg.GetSecretarias();
      //cf.closeConnection(objProg.getConn());
    }catch(SQLException e){
		System.err.println("/******** TDSUB - cwsub");
		e.printStackTrace();
		System.err.println("TDSSPE - cwsub ********/");
    }
    if(areas.size() > 0){
      session.setAttribute("areas",areas);
      
      if((Object)strarea != null && !strarea.equals("nulo"))
      {
      
       
        session.removeAttribute("programas");
        session.removeAttribute("subprogramas");
        try
        {
          objProgramaDAO = new ProgramaDAO(cf);
          ProgramaVO objProgramaVO = new ProgramaVO();
          objProgramaVO.setCodeArea(new Long(strarea));
          programas = (List)objProgramaDAO.findProgramaByCriterea(objProgramaVO, user.getUserGroupName(),user.getCode(),user.getCodeArea());
          cf.closeConnection(objProgramaDAO.getConn());
        }catch(SQLException e){
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
        }
        if(programas.size() > 0)
        {
       
          session.setAttribute("programas",programas);
        
        }/*else
        {
          session.setAttribute("msg","La Secretaria no posee programas inscritos.");
        }*/
     
       }else{
        try
        {
          RepBeneficioOtorgadoDAO objBeneOtor1DAO = new RepBeneficioOtorgadoDAO(cf);
          programas = objBeneOtor1DAO.findProgramaByUserReport(user.getCode(),user.getUserGroupName(), user.getCodeArea());
          cf.closeConnection(objBeneOtor1DAO.getConn());
        }catch(SQLException e){
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
        }
        session.removeAttribute("msg");
        if(programas.size() > 0){
          session.setAttribute("programas",programas);
        }else
        {
          session.setAttribute("msg","No se encontraron programas vigentes a la fecha..");
        }
      }
      if(codePrograma != null)
      {
       
        String codpro = (String)codePrograma;
        if(!codpro.equals("nulo"))
        {
          try
          {
            RepBeneficioOtorgadoDAO objBeneOtor2DAO = new RepBeneficioOtorgadoDAO(cf);
            String strCodeProg = (String)codePrograma;
            subprogramas = objBeneOtor2DAO.findSubProgramaByUserReport(user.getCode(),user.getUserGroupName(),strCodeProg,user.getCodeArea());
            cf.closeConnection(objBeneOtor2DAO.getConn());
          }catch(SQLException e){
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
          }
          session.removeAttribute("msg");
          if(subprogramas.size() > 0){
            session.setAttribute("subprogramas",subprogramas);
          }else
          {
            session.setAttribute("msg","No se encontraron subprogramas asociados a este programa que esten vigentes..");
          }
        }else{
            session.setAttribute("msg","");
            session.removeAttribute("subprogramas");
        }
      }
    }else
    {
      session.setAttribute("msg","No se encontraron sedes vigentes a la fecha..");
    }
    
    Object accion = request.getParameter("acciones");
    Object codeArea = request.getParameter("code");
      if (codeArea == null)
        codeArea = request.getParameter("codearea");
        
    Object codeSubprograma = request.getParameter("codeSubPrograma");
    //Object activacion = request.getParameter("activacion");
     //Object finicial = null;
 //   Object ffinal = null;
    String codeArea1 = (String)codeArea;
    String codeSubprograma1 = (String)codeSubprograma;
    String codePrograma1 = (String)codePrograma;
    //String activacion1 = (String)activacion;
    
    
    // fecha inicial
    Object obdia1 = (Object)request.getParameter("dia1");
    String dia1 = (String)obdia1;
    Object obmes1 = (Object)request.getParameter("mes1");
    String mes1 = (String)obmes1;
    Object obano1 = (Object)request.getParameter("ano1");
    String ano1 = (String)obano1;
    String fechaini = "";
    String fechafinal = "";
    if(obdia1!=null && obmes1!=null && obano1!=null)
    {
      if(!dia1.equals("nulo") && !mes1.equals("nulo") && !ano1.equals("nulo"))
      {
        fechaini = dia1+"/"+mes1+"/"+ano1;
      }else
      {
        //System.out.println("La fecha inicial es incorrecta");
      }
      
    }
    
    // fecha final
    Object obdia2 = (Object)request.getParameter("dia2");
    String dia2 = (String)obdia2;
    Object obmes2 = (Object)request.getParameter("mes2");
    String mes2 = (String)obmes2;
    Object obano2 = (Object)request.getParameter("ano2");
    String ano2 = (String)obano2;
    boolean continuar = true; 
    if(obdia2!=null && obmes2!=null && obano2!=null)
    {
      if(!dia2.equals("nulo") && !mes2.equals("nulo") && !ano2.equals("nulo"))
      {
        fechafinal = dia2+"/"+mes2+"/"+ano2;
      }else
      {//validar fecha
        if(!dia2.equals("nulo") && mes2.equals("nulo") && ano2.equals("nulo"))
        {
          request.setAttribute("errorfecha","La fecha final es incorrecta");
          continuar = false;
        }else
        {
          if(dia2.equals("nulo") && !mes2.equals("nulo") && ano2.equals("nulo"))
          {
            request.setAttribute("errorfecha","La fecha final es incorrecta");
            continuar = false;
          }else
          {
            if(dia2.equals("nulo") && mes2.equals("nulo") && !ano2.equals("nulo"))
            {
              request.setAttribute("errorfecha","La fecha final es incorrecta");
              continuar = false;
            }
          }
        }//fin validar fecha
           
      }
    }
    
      
    if(!fechaini.equals("") && !fechafinal.equals(""))
    {
      String strfinicial = ano1+mes1+dia1;
      String strffinal = ano2+mes2+dia2;
      int finicial = Integer.parseInt(strfinicial.trim());
      int ffinal = Integer.parseInt(strffinal.trim()); 
      if (finicial > ffinal)
      {
         continuar = false; 
         request.setAttribute("errorfecha","La fecha inicial es mayor a la final");
      }
    } 
  
  //  if(obdia1!=null && obmes1!=null && obano1!=null)
 //   {
   //// if(continuar)
    //  {
    
    
    
    String accion1 = (String)accion;
    session.removeAttribute("beneficiosSede");   
    if(accion != null)
    {
      if(accion1.equals("BuscarTodo"))
      {
      String var=user.getCodeArea()+"";
      String var2=strarea;
         //if(var.equals(var2)){
          Collection cobeneficio = null;
          try
          {
            
            ReporteTotalProgramasVO objtotalprog = new ReporteTotalProgramasVO();
            if(codeArea != null && !codeArea1.equals("nulo"))
            {
              objtotalprog.setCodeArea(new Long((String)codeArea));
            }
            if(codePrograma != null && !codePrograma1.equals("nulo"))
            {
              objtotalprog.setCodePrograma(new Long((String)codePrograma));
            }
            if(codeSubprograma != null && !codeSubprograma1.equals("nulo"))
           {
              objtotalprog.setCodeSubprograma(new Long((String)codeSubprograma));
            }
            if(fechaini != null && !fechaini.equals("nulo"))
            {
              objtotalprog.setDesde(fechaini);
            }else{
              objtotalprog.setDesde("");
            }
             if(fechafinal != null && !fechafinal.equals("nulo"))
            {
              objtotalprog.setHasta(fechafinal);
            }else{
              objtotalprog.setHasta("");
            }
//            if(activacion != null && !activacion1.equals("nulo"))
//            {
//              objtotalprog.setActivacion((String)activacion);
//            }
            
            session.setAttribute("Parametros",objtotalprog);
                      
            objProg = new ReporteTotalProgramasDAO(cf);
            objtotalprog = objProg.getFilters(objtotalprog);
            cobeneficio =  objProg.GetTotalProgSubpro(objtotalprog);
            cf.closeConnection(objProg.getConn());
            
            if(cobeneficio != null){
              if(cobeneficio.size() > 0)
              {
                session.setAttribute("Beneficios",cobeneficio);
                session.setAttribute("Filters",objtotalprog);
              }else
              {
                session.removeAttribute("Beneficios");
              }
            }
            objtotalprog = null;
          }catch(SQLException e)
          {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
          }
      //}
    }}else{
    session.removeAttribute("Beneficios");
    }
 // }
//}
    Object obIR = request.getParameter("seleccionar");
    if(obIR == null || accion.equals("BuscarSubprogrmas") || accion.equals("areas"))
    {
      return mapping.findForward("success");
    }else
    {
      return mapping.findForward("ir");
    }
    
  }
}